package com.whalehearing.tingyou.common.utils;

/**
 * @author: shensh
 * @Desc:
 * @create: 2025-03-19 15:26
 **/
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class JsonUtil {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 将对象序列化为 JSON 字符串（支持任意类型）
     */
    public <T> String serializeToJson(T data) {
        try {
            return objectMapper.writeValueAsString(data);
        } catch (Exception e) {
            throw new RuntimeException("Failed to serialize data to JSON", e);
        }
    }

    /**
     * 将 JSON 字符串反序列化为对象（支持任意类型）
     */
    public <T> T deserializeFromJson(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException("Failed to deserialize JSON to data", e);
        }
    }

    /**
     * 将 JSON 字符串反序列化为复杂类型（支持泛型类型，如 Map<String, List<T>>）
     */
    public <T> T deserializeFromJson(String json, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (Exception e) {
            throw new RuntimeException("Failed to deserialize JSON to data", e);
        }
    }
}

